package com.xxxx.server.task;



import com.xxxx.server.pojo.MailLog;
import com.xxxx.server.service.IMailLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class ResendMsg {

    @Autowired
    private IMailLogService mailLogService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    // 最大投递次数
    private static final int MAX_TRY_COUNT = 3;

    /**
     * 每30s拉取投递失败的消息, 重新投递
     */
    @Scheduled(cron = "0/30 * * * * ?")
    public void resend(){
        //获取全部投递消息数据
        List<MailLog> mailLogs = mailLogService.listAllFailed();
        if(mailLogs != null && mailLogs.size() > 0){
            for(MailLog mailLog : mailLogs){
                String msgId = mailLog.getMsgId();
                if (mailLog.getCount() < MAX_TRY_COUNT) {
                    // 重试次数+1
                    mailLogService.updateCount(mailLog);
                    CorrelationData correlationData = new CorrelationData(msgId);

                    //根据消息id获取邮箱地址
                    String email = mailLogService.getEmailByMsgId(mailLog.getMsgId());
                    // 重新投递
                    rabbitTemplate.convertAndSend(mailLog.getExchange(), mailLog.getRouteKey(), email , correlationData);
                }
            }
        }
    }
}
